package com.paradox.rpc.protocol.Netty;

import com.paradox.rpc.protocol.ParadoxServer;
import com.paradox.rpc.registry.Registry;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

public class NettyServer implements ParadoxServer {
    private Registry registry;

    public NettyServer(Registry registry) {
        this.registry = registry;
    }

    @Override
    public void start() {
        ServerBootstrap bootstrap=new ServerBootstrap();
        NioEventLoopGroup group=new NioEventLoopGroup(1);
        try {
            bootstrap.group(group).channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline=socketChannel.pipeline();
                            pipeline.addLast("encoder",new ObjectEncoder());
                            pipeline.addLast("decoder",new ObjectDecoder(10240, ClassResolvers.cacheDisabled(null)));
                            pipeline.addLast(new NettyServerHandler(registry));
                        }
                    });

            bootstrap.bind("localhost",9000);
        }catch (Exception e){
            group.shutdownGracefully();
        }

    }
}
